package org.fastsyncer.parser.webservice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.entity.Mapping;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.common.entity.WebServiceConfig;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.connector.ws.WebServiceConnector;
import org.fastsyncer.parser.util.ConvertUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebserviceParser {

	// 实现单例模式的方法，通过方法来实现实例化
	// 声明一个私有的静态属性，使只被实例化一次
	private static final WebserviceParser instance = new WebserviceParser();

	// 声明一个私有的构造方法，使别人不能随便new对象
	// 它只被调用一次，实例存在之后就不再调用了
	private WebserviceParser() {
	}

	// 声明一个公共的静态方法，外界通过调用这个方法来得到唯一的实例
	public static WebserviceParser getInstance() {
		return instance;
	}

	private static Logger logger = LoggerFactory.getLogger(WebserviceParser.class);

	/**
	 * 推送目标源
	 * 
	 * @param mappingTask
     * @param eventType
     *            同步事件
	 * @param msg
	 *            同步数据
	 * @return 执行结果true/false
	 * @throws Exception
	 */
	public boolean send(MappingTask mappingTask, String eventType, JSONArray msg) throws Exception {
		// 1.同步数据源、目标源属性
		Mapping sourceMapping = mappingTask.getSourceMapping();
		Mapping targetMapping = mappingTask.getTargetMapping();

        // 2.对数据进行转换处理
        Map<String, Object> convert = ConvertUtil.convert(sourceMapping, targetMapping, msg);
		
		// 3.转换为JSON字符串
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("EVENTTYPE", eventType);
        res.put("DATA", convert);
		String objToJson = JsonUtil.objToJson(res);
		logger.info(objToJson);

		// 4.推送目标源
		WebServiceConfig config = (WebServiceConfig) targetMapping.getConfig();
		Object r = WebServiceConnector.getInstance().send(config.getUrl(), config.getMethod(), objToJson);
		logger.info(r.toString());
		return true;
	}

    public Integer[] syncTarget(MappingTask mappingTask, List<Map<String, Object>> rows, Integer[] pos, ConcurrentLinkedQueue<JSONObject> reasonQuene) {
        // 批量条数
        int size = rows.size();
        // 总数和成功数
        int total = size;
        int success = 0;
        try {
            // 1.同步数据源、目标源属性
            Mapping targetMapping = mappingTask.getTargetMapping();
            WebServiceConfig config = (WebServiceConfig) targetMapping.getConfig();
            
            for (Map<String, Object> map : rows) {
                Map<String, Object> res = new HashMap<String, Object>();
                res.put("EVENTTYPE", ConnectorConstant.OPERTION_INSERT);
                res.put("DATA", map);
                // 2.转换为JSON字符串
                String objToJson = JsonUtil.objToJson(res);
                logger.info(objToJson);

                // 3.推送目标源
                WebServiceConnector.getInstance().send(config.getUrl(), config.getMethod(), objToJson);
                success++;
            }
        } catch (Exception e) {
            try {
                // 记录错误信息
                JSONObject err = new JSONObject();
                if(pos != null && pos.length == 2){
                    err.put("startPos", pos[0]);
                    err.put("endPos", pos[1]);
                }
                err.put("cause", e.getCause());
                err.put("message", e.getMessage());
                reasonQuene.offer(err);
            } catch (JSONException e1) {
                logger.error("When logging an error message: Converts a JSONObject exception!");
            }
        }
        return new Integer[] { total, success };
    }

}
